package cn.wangchao.basic.service.impl;

import cn.wangchao.basic.constants.BaseConstant;
import cn.wangchao.basic.dto.LoginDto;
import cn.wangchao.basic.dto.RegisterDto;
import cn.wangchao.basic.dto.WechatDto;
import cn.wangchao.basic.exception.BusinessException;
import cn.wangchao.basic.service.ILoginService;
import cn.wangchao.basic.util.AjaxResult;
import cn.wangchao.basic.util.HttpClientUtils;
import cn.wangchao.basic.util.MD5Utils;
import cn.wangchao.basic.util.StrUtils;
import cn.wangchao.user.domain.Logininfo;
import cn.wangchao.user.domain.User;
import cn.wangchao.user.domain.Wxuser;
import cn.wangchao.user.mapper.LogininfoMapper;
import cn.wangchao.user.mapper.UserMapper;
import cn.wangchao.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import sun.security.krb5.internal.PAData;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String,Object> account(LoginDto dto) {
        String password = dto.getPassword();
        String username = dto.getUsername();
        Integer type = dto.getType();
        //非空校验
        if (StringUtils.isEmpty(password)
                || StringUtils.isEmpty(username)
                || StringUtils.isEmpty(type)
        ){
            throw new BusinessException("参数不能空,请你好好看一下!");
        }
        //拿数据比对
        Logininfo logininfo = logininfoMapper.loadByUsernameAndpassword(username,type);
        if (logininfo == null){
            throw new BusinessException("账户信息不正确,请重新输入");
        }
        //校验密码是否正确
        String salt = logininfo.getSalt();
        String loginPassword = MD5Utils.encrypByMd5(password + salt);
        if (loginPassword.equals(logininfo.getPassword())){
            throw new BusinessException("账号或者密码不正确,请重新输入");
        }
        //保存数据到Redis,key是token
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        //有些数据不能给用户看,给null
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;

    }

    /**
     * 微信三方扫码登录
     * @param dto
     * @return
     */
    @Override
    public AjaxResult wechat(WechatDto dto) {
        String code = dto.getCode();
        if (StringUtils.isEmpty(code)){
            System.out.println("code错了,快看看");
        }
        //从请求头中获取token跟openid
        String tokenUrl = BaseConstant.WechatConstants.TOKEN_URL
                .replace("APPID", BaseConstant.WechatConstants.APPID)
                .replace("SECRET", BaseConstant.WechatConstants.SECRET)
                .replace("CODE", code);
        //拿到请求头,为json格式的字符串
        String httpGet = HttpClientUtils.httpGet(tokenUrl);
        //将字符串转换为json对象
        JSONObject jsonObject = JSONObject.parseObject(httpGet);
        //从json对象中拿到token,openid
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        //根据openid查询wxuser表的数据,看是否存在
        Wxuser wxuser = wxuserMapper.loadByOpenId(openid);
        //判断是否wxuser存在并且user_id不为空

        if (wxuser != null && wxuser.getUserId() != null){
            //保存数据到Redis,key是token
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            //有些数据不能给用户看,给null
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            map.put("logininfo",logininfo);
            return new AjaxResult().my().setResultObj(map);
        }
        String params ="?accessToken=" + accessToken +"&openId=" + openid;
        return new AjaxResult().my().setSuccess(false).setResultObj(params);
    }

    @Override
    public Map<String,Object> binder(WechatDto dto) {
        String phone = dto.getPhone();
        String password = dto.getPassword();
        String accessToken = dto.getAccessToken();
        String openId = dto.getOpenId();
        //非空判断
        if (StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(accessToken)
                || StringUtils.isEmpty(openId)
        ){
            throw new BusinessException("参数不能为空!");
        }
        User user = userMapper.loadByphone(dto.getPhone());
        Logininfo logininfo = null;
        if (user != null){
            //存在查出来
            logininfo = logininfoMapper.loadByUserId(user.getId());

        }else {
            //不存在生成新的t_user,t_logininfo
            user = dto2User(dto);
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }
        //根据token跟openID去微信拿基本信息
        String WxuserUrl = BaseConstant.WechatConstants.WXUSER_URL
                .replace("ACCESS_TOKEN", dto.getAccessToken())
                .replace("OPENID", dto.getOpenId());
        String httpGet = HttpClientUtils.httpGet(WxuserUrl);
        //根据基本信息生成wxuser
        Wxuser wxuser = JSONObject.parseObject(httpGet, Wxuser.class);
        //根据wxuser绑定user
        wxuser.setUserId(user.getId());
        //保存数据,免密登陆
        wxuserMapper.save(wxuser);
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        //有些数据不能给用户看,给null
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;
    }
    //保存loginof
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }
    //保存user
    private User dto2User(WechatDto dto) {
        User user = new User();
        user.setUsername(dto.getPhone());
        user.setPhone(dto.getPhone());
        String salt = StrUtils.getComplexRandomString(16);
        String md5 = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5);
        return user;
    }

}
